import 'dart:async';

import 'package:flutter/material.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'login.dart';
import 'constants.dart';

void main() => runApp(DisplaySignCodeWidget());

class DisplaySignCodeWidget extends StatefulWidget {
  @override
  _DisplaySignCodeWidgetState createState() => _DisplaySignCodeWidgetState();
}

class _DisplaySignCodeWidgetState extends State<DisplaySignCodeWidget> {
  TextEditingController classNameController = TextEditingController();
  TextEditingController classTimeController = TextEditingController();
  List<bool> isChecklists = [false, false, false, false];
  String signCode = '';

  @override
  void initState() {
    super.initState();
    // 在初始化阶段调用startCheckIn方法
    startCheckIn();
  }

  @override
  void dispose() {
    // Clean up the controllers when the widget is disposed.
    classNameController.dispose();
    classTimeController.dispose();
    super.dispose();
  }

  // Add your server's URL and JWT token here
  // final String serverUrl = 'http://10.161.4.248:8080/v1/startSign';
  final String serverUrl = AppConstants.serverUrl;
  // Method to send the POST request
  Future<void> startCheckIn() async {
    String jwtToken = await retrieveJwtToken('access_token');
    if (jwtToken == '') {
      print('No JWT token found.');
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => Login()),
      );
      return;
    }
    try {
      var response = await http.post(
        Uri.parse('$serverUrl/v1/startSign'),
        headers: <String, String>{
          'Content-Type': 'application/json',
          'Authorization': 'Bearer $jwtToken',
        },
        body: jsonEncode(<String, dynamic>{
          'class_id': 7,
          'duration': '10',
        }),
      );

      if (response.statusCode == 201) {
        // Handle successful response
        print('Check-in initiated successfully.');
        // 解析JSON响应并存储sign_code
        final Map<String, dynamic> responseData = jsonDecode(response.body);
        if (responseData.containsKey('sign_code')) {
          setState(() {
            signCode = responseData['sign_code'];
          });
        }
      } else {
        // Handle error response
        print('Failed to initiate check-in: ${response.body}');
      }
    } catch (e) {
      // Handle any exceptions
      print('Error occurred while initiating check-in: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    final width = size.width;
    final height = size.height;
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.white,
          centerTitle: true,
          title: Text(
            '发起签到',
            style: TextStyle(fontSize: 20, color: Colors.black),
          ),
          leading: IconButton(
            icon: Icon(
              Icons.arrow_back,
              color: Colors.black54,
            ),
            onPressed: () {
              // 返回按钮功能
              Navigator.pop(context);
            },
          ),
        ),
        body: Container(
          width: width,
          height: height,
          color: Colors.white, // 设置底色为浅灰色
          child: Column(children: [
            SizedBox(height: 0.02 * height),
            Container(
                width: 0.9 * width,
                height: 0.07 * height,
                child: Row(children: [
                  SizedBox(width: 0.03 * width),
                  Text(
                    '《软件工程》 李金喜老师 8:30-11:50',
                    style: TextStyle(fontSize: 20),
                    textAlign: TextAlign.center,
                    overflow: TextOverflow.ellipsis,
                  )
                ])),
            SizedBox(height: 0.02 * height),
            Container(
              width: 0.9 * width,
              height: 0.15 * height,
              decoration: BoxDecoration(
                color: Colors.white, // 设置矩形底色为白色
                borderRadius: BorderRadius.circular(8), // 设置圆角
                boxShadow: [
                  BoxShadow(color: Colors.grey.shade200, blurRadius: 8)
                ],
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    '签到方式:',
                    style: TextStyle(fontSize: 18),
                  ),
                  SizedBox(width: 0.05 * width),
                  Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Row(
                        children: [
                          Checkbox(
                            value: isChecklists[0],
                            onChanged: (bool? value) {
                              // TODO
                              setState(() {
                                isChecklists[0] = value!;
                              });
                            },
                          ),
                          Text('WIFI', style: TextStyle(fontSize: 19)),
                        ],
                      ),
                      Row(
                        children: [
                          Checkbox(
                            value: isChecklists[1],
                            onChanged: (bool? value) {
                              // TODO
                              setState(() {
                                isChecklists[1] = value!;
                              });
                            },
                          ),
                          Text('NFC', style: TextStyle(fontSize: 19)),
                        ],
                      ),
                    ],
                  ),
                  SizedBox(width: 0.05 * width),
                  Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Row(
                        children: [
                          Checkbox(
                            value: isChecklists[2],
                            onChanged: (bool? value) {
                              // TODO
                              setState(() {
                                isChecklists[2] = value!;
                              });
                            },
                          ),
                          Text('扫码', style: TextStyle(fontSize: 19)),
                        ],
                      ),
                      Row(
                        children: [
                          Checkbox(
                            value: isChecklists[3],
                            onChanged: (bool? value) {
                              // TODO
                              setState(() {
                                isChecklists[3] = value!;
                              });
                            },
                          ),
                          Text('蓝牙', style: TextStyle(fontSize: 19)),
                        ],
                      ),
                    ],
                  ),
                ],
              ),
            ),
            SizedBox(height: 0.02 * height),
            Container(
              width: 0.9 * width,
              height: 0.38 * height,
              decoration: BoxDecoration(
                color: Colors.white, // 设置矩形底色为白色
                borderRadius: BorderRadius.circular(8), // 设置圆角
                boxShadow: [
                  BoxShadow(color: Colors.grey.shade200, blurRadius: 8)
                ],
              ),
              child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    QrImageView(
                      data: signCode,
                      version: QrVersions.auto,
                      size: 200.0,
                    ),
                    Text(
                      "如果无法扫描，请输入下面签到码",
                      style: TextStyle(fontSize: 18),
                    ),
                    SizedBox(height: 0.01 * height),
                    Container(
                      padding: EdgeInsets.all(8.0), // 设置内边距
                      decoration: BoxDecoration(
                        border: Border.all(
                          color: Colors.black,
                          width: 2.0,
                        ),
                        borderRadius: BorderRadius.circular(8.0), // 设置边框圆角
                      ),
                      child: Text(
                        signCode,
                        style: TextStyle(
                          fontSize: 18.0,
                          color: Colors.black,
                        ),
                      ),
                    )
                  ]),
            ),
          ]),
        ),
      ),
    );
  }
}
